package com.sth.shishan;

import org.junit.Test;
import redis.clients.jedis.Jedis;

/**
 * @Author: sitianhong
 * @Description:
 * @Since: create in 2021/6/13 0013 16:31
 */
public class RedisDemo2 {

    private static final String X36 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static final String[] X36_ARRAY = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z".split(",");
    Jedis jedis = new Jedis("127.0.0.1", 6378);

    @Test // 实现 社交网站点击追踪机制1
    public void demo1() {
        String shortUrl = "http:www.sith.com2";
        getShortUrl(shortUrl);
        incrShortAccessCount(shortUrl);
        long shortAccessCount = getShortAccessCount(shortUrl);
        System.out.println("访问次数 " + shortAccessCount);
    }

    public String getShortUrl(String url) {

        Long shortUrlSeed = jedis.incr("short_url_seed");
        System.out.println("页面展示的地址为: " + url);
        StringBuffer sb = new StringBuffer();
        if (shortUrlSeed == 0) {
            sb.append("0");
        }
        while (shortUrlSeed > 0) {
            sb.append(X36_ARRAY[(int) (shortUrlSeed % 36)]);
            shortUrlSeed = shortUrlSeed / 36;
        }
        String shortUrl = sb.reverse().toString();
        jedis.hset("short_url_access_count", shortUrl, "0");
        jedis.hset("short_url_access_maping", shortUrl, url);
        return shortUrl;
    }

    // 访问次数的增长
    public void incrShortAccessCount(String shortUrl) {
        jedis.hincrBy("short_url_access_count", shortUrl, 1);
    }

    public long getShortAccessCount(String shortUrl) {
        return Long.valueOf(jedis.hget("short_url_access_count", shortUrl));
    }
}
